package com.shy.config.handler;

import com.shy.config.common.TokenConstants;
import com.shy.config.model.R;
import com.shy.config.model.SecurityUser;
import com.shy.config.util.JWTUtils;
import com.shy.config.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;

/**
 * 登录成功处理器
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        /*从security获取认证用户信息*/
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        /*生成token*/
        String token = JWTUtils.createJWT(securityUser);

        /*获取记住我参数*/
        boolean rememberMe = Boolean.parseBoolean(request.getParameter("rememberMe"));
        /*判断是否记住我*/
        if (rememberMe) {
            /*选中记住我，存放时间为30天*/
            stringRedisTemplate.opsForValue().set(TokenConstants.TOKEN_PREFIX + token, "", Duration.ofSeconds(TokenConstants.REMEMBER_ME_TIME));
        }else {
            /*未选中记住我，存放时间为8小时*/
            /*将token存放到redis中，未选中记住我存放时间为8小时*/
            stringRedisTemplate.opsForValue().set(TokenConstants.TOKEN_PREFIX + token, "", Duration.ofSeconds(TokenConstants.TOKEN_TIME));
        }
        /*响应数据给前端*/
        ResponseUtils.write(response, R.success(token));
        System.out.println("用户已登录.....");
    }
}
